﻿using System.Collections.Generic;
using System.Data;
using System.Linq;
using DataScripter.Containers;
using DataScripter.Scripting.Processes.Morphs;
using DataScripter.Scripting.Processes.Output;

namespace DataScripter.Scripting.Processes
{
    public class MorphProcess : BaseProcess
    {
        private IMorphActionsDefinition MorphActions { get; set; }

        public MorphProcess(string name, IContainer container) : base(name, container)
        {
        }

        #region Overrides of BaseProcess

        public override void Initialize(Dictionary<string, string> parameters)
        {
            MorphActions = GetTypedParameter<IMorphActionsDefinition>(parameters, "Actions");
        }

        public override IProcessOutput Run()
        {
            RunParents();
            if (State == ProcessState.Error)
                return null;

            IProcess inputProcess = InputProcesses[0];
            DataSetProcessOutput processOutput = (DataSetProcessOutput) inputProcess.Output;

            DataSet dataSet = processOutput.DataSet;
            List<string> tables = dataSet.Tables.OfType<DataTable>().Select(t => t.TableName).ToList();
            foreach (string table in tables)
            {
                foreach (ITableMorphAction morphAction in MorphActions.GetMorphActionsForTable(table))
                {
                    morphAction.Apply(dataSet, table);
                }
            }

            Output = processOutput;
            State = ProcessState.Ended;
            return Output;
        }

        #endregion
    }
}
